package utils

import (
	"fmt"
	"github.com/yang3yen/xxtea-go/xxtea"
	"hash/crc32"
	"io"
	"strconv"
	"strings"
)

var key = []byte{97, 3, 143, 112, 52, 24, 151, 153, 58, 235, 231, 139, 133, 151, 36, 52}

var metadata1Template = `{
    "metrics": {
        "el": 0,
        "script": 0,
        "h": 0,
        "batt": 0,
        "perf": 0,
        "auto": 0,
        "tz": 0,
        "fp2": 0,
        "lsubid": 0,
        "browser": 0,
        "capabilities": 0,
        "gpu": 0,
        "dnt": 0,
        "math": 0,
        "tts": 1,
        "input": 0,
        "canvas": 0,
        "captchainput": 0,
        "pow": 0
    },
    "start": <startDate>,
    "interaction": {
        "clicks": 7,
        "touches": 0,
        "keyPresses": 25,
        "cuts": 0,
        "copies": 0,
        "pastes": 0,
        "keyPressTimeIntervals": [
            2,
            90009,
            6718,
            273,
            270,
            248,
            256,
            186,
            152
        ],
        "mouseClickPositions": [
            "916,163",
            "1170,165",
            "1170,165",
            "1170,165",
            "1262,165",
            "1536,174",
            "1352,215"
        ],
        "keyCycles": [
            2,
            1,
            558,
            104,
            114,
            105,
            90,
            95,
            90,
            84
        ],
        "mouseCycles": [
            56,
            396,
            75,
            72,
            72,
            109,
            113,
            110
        ],
        "touchCycles": []
    },
    "scripts": {
        "dynamicUrls": [
            "https://images-na.ssl-images-amazon.com/images/I/31YXrY93hfL.js",
            "https://images-na.ssl-images-amazon.com/images/I/61lemL2h6EL._RC|11Y+5x+kkTL.js,51KMV3Cz2XL.js,31x4ENTlVIL.js,31f4+QIEeqL.js,01N6xzIJxbL.js,518BI433aLL.js,01rpauTep4L.js,31QZSjMuoeL.js,61ofwvddDeL.js,01KsMxlPtzL.js_.js?AUIClients/AmazonUI&amp;KK9dlo3A#412402-T1.412405-T1",
            "https://images-na.ssl-images-amazon.com/images/I/21G215oqvfL._RC|21OJDARBhQL.js,218GJg15I8L.js,31lucpmF4CL.js,2119M3Ks9rL.js,51FZO4MwWKL.js_.js?AUIClients/AuthenticationPortalAssets",
            "https://images-na.ssl-images-amazon.com/images/I/01wGDSlxwdL.js?AUIClients/AuthenticationPortalInlineAssets",
            "https://images-na.ssl-images-amazon.com/images/I/31s9T4yFQdL.js?AUIClients/CVFAssets",
            "https://images-na.ssl-images-amazon.com/images/I/81DRuMmUGiL.js?AUIClients/SiegeClientSideEncryptionAUI",
            "https://images-na.ssl-images-amazon.com/images/I/31jdfgcsPAL.js?AUIClients/AmazonUIFormControlsJS",
            "https://images-na.ssl-images-amazon.com/images/I/81OcTocfWrL.js?AUIClients/FWCIMAssets"
        ],
        "inlineHashes": [
            -1746719145,
            -2133588911,
            -475296311,
            -314038750,
            1656598380,
            -1635057205,
            319522664,
            -710277188,
            318224283,
            -136301235,
            585973559,
            -1611905557,
            1800521327,
            2118020403,
            1532181211,
            -1303231473,
            1318378478
        ],
        "elapsed": 4,
        "dynamicUrlCount": 8,
        "inlineHashesCount": 17
    },
    "history": {
        "length": 3
    },
    "battery": {},
    "performance": {
        "timing": {
            "connectStart": 1660375690219,
            "navigationStart": 1660375690217,
            "loadEventEnd": 1660375691169,
            "domLoading": 1660375690640,
            "secureConnectionStart": 0,
            "fetchStart": 1660375690219,
            "domContentLoadedEventStart": 1660375690878,
            "responseStart": 1660375690628,
            "responseEnd": 1660375690852,
            "domInteractive": 1660375690877,
            "domainLookupEnd": 1660375690219,
            "redirectStart": 0,
            "requestStart": 1660375690224,
            "unloadEventEnd": 1660375690635,
            "unloadEventStart": 1660375690635,
            "domComplete": 1660375691159,
            "domainLookupStart": 1660375690219,
            "loadEventStart": 1660375691159,
            "domContentLoadedEventEnd": 1660375690878,
            "redirectEnd": 0,
            "connectEnd": 1660375690219
        }
    },
    "automation": {
        "wd": {
            "properties": {
                "document": [],
                "window": [],
                "navigator": []
            }
        },
        "phantom": {
            "properties": {
                "window": []
            }
        }
    },
    "end": <endDate>,
    "timeZone": 8,
    "flashVersion": null,
    "plugins": "PDF Viewer Chrome PDF Viewer Chromium PDF Viewer Microsoft Edge PDF Viewer WebKit built-in PDF ||2560-1440-1400-24-*-*-*",
    "dupedPlugins": "PDF Viewer Chrome PDF Viewer Chromium PDF Viewer Microsoft Edge PDF Viewer WebKit built-in PDF ||2560-1440-1400-24-*-*-*",
    "screenInfo": "2560-1440-1400-24-*-*-*",
    "lsUbid": "X05-4056731-4724712:1652859624",
    "referrer": "https://www.amazon.com/",
    "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.66 Safari/537.36",
    "location": "https://www.amazon.com/ap/signin?openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.com%2F%3Fref_%3Dnav_custrec_signin&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=usflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&",
    "webDriver": false,
    "capabilities": {
        "css": {
            "textShadow": 1,
            "WebkitTextStroke": 1,
            "boxShadow": 1,
            "borderRadius": 1,
            "borderImage": 1,
            "opacity": 1,
            "transform": 1,
            "transition": 1
        },
        "js": {
            "audio": true,
            "geolocation": true,
            "localStorage": "supported",
            "touch": false,
            "video": true,
            "webWorker": true
        },
        "elapsed": 0
    },
    "gpu": {
        "vendor": "Google Inc. (NVIDIA)",
        "model": "ANGLE (NVIDIA, NVIDIA GeForce GTX 1660 Direct3D11 vs_5_0 ps_5_0, D3D11)",
        "extensions": [
            "ANGLE_instanced_arrays",
            "EXT_blend_minmax",
            "EXT_color_buffer_half_float",
            "EXT_disjoint_timer_query",
            "EXT_float_blend",
            "EXT_frag_depth",
            "EXT_shader_texture_lod",
            "EXT_texture_compression_bptc",
            "EXT_texture_compression_rgtc",
            "EXT_texture_filter_anisotropic",
            "EXT_sRGB",
            "KHR_parallel_shader_compile",
            "OES_element_index_uint",
            "OES_fbo_render_mipmap",
            "OES_standard_derivatives",
            "OES_texture_float",
            "OES_texture_float_linear",
            "OES_texture_half_float",
            "OES_texture_half_float_linear",
            "OES_vertex_array_object",
            "WEBGL_color_buffer_float",
            "WEBGL_compressed_texture_s3tc",
            "WEBGL_compressed_texture_s3tc_srgb",
            "WEBGL_debug_renderer_info",
            "WEBGL_debug_shaders",
            "WEBGL_depth_texture",
            "WEBGL_draw_buffers",
            "WEBGL_lose_context",
            "WEBGL_multi_draw"
        ]
    },
    "dnt": null,
    "math": {
        "tan": "-1.4214488238747245",
        "sin": "0.8178819121159085",
        "cos": "-0.5753861119575491"
    },
    "timeToSubmit": <timeToSubmit>,
    "form": {
        "email": {
            "clicks": 4,
            "touches": 0,
            "keyPresses": 24,
            "cuts": 0,
            "copies": 0,
            "pastes": 0,
            "keyPressTimeIntervals": [
                90011,
                6718,
                273,
                270,
                248,
                256,
                186,
                152,
                138
            ],
            "mouseClickPositions": [
                "46.333251953125,12.40625",
                "46.333251953125,12.40625",
                "46.333251953125,12.40625",
                "138.333251953125,12.40625"
            ],
            "keyCycles": [
                1,
                558,
                104,
                114,
                105,
                90,
                95,
                90,
                84,
                89
            ],
            "mouseCycles": [
                3880,
                71,
                71,
                109
            ],
            "touchCycles": [],
            "width": 296,
            "height": 31,
            "totalFocusTime": 16707,
            "checksum": "7DF79A91",
            "autocomplete": false,
            "prefilled": false
        },
        "ap-credential-autofill-hint": {
            "clicks": 0,
            "touches": 0,
            "keyPresses": 1,
            "cuts": 0,
            "copies": 0,
            "pastes": 0,
            "keyPressTimeIntervals": [],
            "mouseClickPositions": [],
            "keyCycles": [
                1
            ],
            "mouseCycles": [],
            "touchCycles": [],
            "width": 0,
            "height": 0,
            "totalFocusTime": 1,
            "autocomplete": false,
            "prefilled": false
        }
    },
    "canvas": {
        "hash": -1979214887,
        "emailHash": 1560122560,
        "histogramBins": [
            13145,
            26,
            36,
            27,
            63,
            44,
            32,
            31,
            31,
            119,
            30,
            27,
            23,
            28,
            78,
            40,
            33,
            15,
            117,
            34,
            39,
            24,
            11,
            14,
            61,
            20,
            26,
            44,
            42,
            37,
            44,
            28,
            43,
            21,
            26,
            101,
            30,
            32,
            19,
            35,
            31,
            23,
            14,
            56,
            49,
            18,
            17,
            38,
            13,
            24,
            58,
            24,
            17,
            22,
            14,
            42,
            25,
            13,
            27,
            53,
            38,
            32,
            37,
            21,
            26,
            25,
            39,
            10,
            15,
            22,
            15,
            32,
            121,
            12,
            47,
            26,
            21,
            27,
            29,
            44,
            17,
            24,
            19,
            55,
            28,
            22,
            57,
            44,
            23,
            34,
            25,
            42,
            71,
            13,
            14,
            26,
            48,
            13,
            52,
            73,
            39,
            35,
            490,
            26,
            146,
            47,
            7,
            24,
            13,
            36,
            45,
            18,
            13,
            27,
            36,
            12,
            33,
            26,
            33,
            26,
            22,
            18,
            30,
            12,
            25,
            41,
            68,
            71,
            79,
            71,
            39,
            14,
            36,
            10,
            17,
            19,
            26,
            54,
            23,
            30,
            15,
            13,
            16,
            21,
            12,
            32,
            69,
            26,
            12,
            12,
            57,
            68,
            14,
            99,
            20,
            28,
            19,
            16,
            12,
            16,
            16,
            23,
            13,
            24,
            51,
            17,
            11,
            18,
            45,
            46,
            12,
            19,
            43,
            21,
            10,
            17,
            54,
            14,
            36,
            21,
            5,
            17,
            16,
            127,
            39,
            9,
            13,
            7,
            17,
            54,
            18,
            23,
            20,
            19,
            23,
            58,
            49,
            14,
            41,
            18,
            48,
            9,
            39,
            12,
            46,
            36,
            35,
            42,
            59,
            37,
            14,
            66,
            82,
            15,
            32,
            25,
            17,
            29,
            24,
            28,
            47,
            28,
            24,
            53,
            29,
            39,
            38,
            103,
            61,
            40,
            35,
            46,
            45,
            15,
            35,
            24,
            74,
            44,
            24,
            19,
            70,
            92,
            46,
            19,
            63,
            23,
            114,
            48,
            82,
            36,
            35,
            97,
            32,
            40,
            42,
            13538
        ]
    },
    "token": {
        "isCompatible": true,
        "pageHasCaptcha": 0
    },
    "auth": {
        "form": {
            "method": "post"
        }
    },
    "errors": [],
    "version": "4.0.0"
}`

func XXTEADecrypt(cipherText string) (plainText []byte) {
	plainText, _ = xxtea.DecryptBase64(cipherText, key, false, 0)

	return
}

func XXTEAEncrypt(plainText []byte) (cipherText string) {
	cipherText, err := xxtea.EncryptBase64(plainText, key, false, 0)
	fmt.Println(err)
	return
}

func Crc3(str string) int {
	ieee := crc32.NewIEEE()
	_, err := io.WriteString(ieee, str)
	if err != nil {
		return 0
	}

	return int(ieee.Sum32())
}

func EncodeHex(crc3 int) string {
	return strings.ToUpper(strconv.FormatInt(int64(crc3), 16))
}

func Encrypt(plainText []byte) string {
	cipherText := XXTEAEncrypt([]byte(fmt.Sprintf("%s#%s", EncodeHex(Crc3(string(plainText))), plainText)))
	return fmt.Sprintf("ECdITeCs:%s", cipherText)
}

func Decrypt(cipherText string) (string, string, bool) {
	cipherText = strings.Replace(cipherText, "ECdITeCs:", "", -1)
	plainText := XXTEADecrypt(cipherText)

	return string(plainText), "", false
	//return strings.Cut(string(plainText), "#")
}

func GeneratedMetadata1() string {
	//h, _ := time.ParseDuration(fmt.Sprintf("-%ds", RandomInt(60, 180)))
	//currentDate := time.Now()
	//startDate := currentDate.Add(h).UnixMilli()
	//endDate := time.Now().UnixMilli()
	//timeToSubmit := endDate - startDate
	//result := strings.Replace(metadata1Template, `<startDate>`, strconv.Itoa(int(startDate)), -1)
	//result = strings.Replace(result, `<endDate>`, strconv.Itoa(int(endDate)), -1)
	//result = strings.Replace(result, `<timeToSubmit>`, strconv.Itoa(int(timeToSubmit)), -1)
	//
	//dst := &bytes.Buffer{}
	//if err := json.Compact(dst, []byte(result)); err != nil {
	//	panic(err)
	//}
	//fmt.Println(dst.String())
	//return result
	return ""
}
